package com.colin.log.mvc;

import com.colin.log.util.IdUtil;
import com.colin.log.util.IpUtil;
import com.colin.log.util.LogUtil;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * MVC 日志跟踪拦截器
 * 在拦截器中尽量避免使用HttpServletRequest
 * 防止无法二次获取
 */
public class MvcLogInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 设置日志参数
        String traceId = request.getHeader(LogUtil.LOG_PARAM_TRACE_ID);
        if (traceId == null || traceId.length() == 0) {
            traceId = IdUtil.getUUID();
        }
        MDC.put(LogUtil.LOG_PARAM_TRACE_ID, traceId);
        MDC.put(LogUtil.LOG_PARAM_CLIENT_IP, IpUtil.getClientIp(request));
        MDC.put(LogUtil.LOG_PARAM_URI, request.getRequestURI());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.clear();
    }
}
